//
//  ZHomeVC.m
//  WeClubs
//
//  Created by Zed Link on 26/3/2017.
//  Copyright © 2017 Zed. All rights reserved.
//

#import "ZHomeVC.h"
#import "ZQRCodeScanner.h"
#import "ZUserInfo.h"
#import "ZVerticalButton.h"
#import "ZCommentHeader.h"
#import "UIButton+ZUtilities.h"
#import "UINavigationBar+ZUtilities.h"
#import <SDCycleScrollView.h>
#import <objc/runtime.h>

#import "ZClubCardCell.h"
#import "ZActivityCardCell.h"
#import "ZTweetCardCell.h"

#define NAVBAR_CHANGE_START 0       // 导航栏颜色开始渐变的偏移值
#define NAVBAR_CHANGE_POINT (self.view.width/750.f*400.f - 64)/2      // 导航栏前景色切换值
#define NAVBAR_CHANGE_TOTAL (self.view.width/750.f*400.f - 64)      // 导航栏颜色渐变的持续值

NSString * const HomeHeaderReuseID = @"ZHomeHeaderReuseID";
NSString * const ClubCardCellReuseID = @"ZHomeClubCardCellReuseID";
NSString * const ActivityCardCellReuseID = @"ZHomeActivityCardCellReuseID";
NSString * const TweetCardCellReuseID = @"ZHomeTweetCardCellReuseID";


@interface ZHomeVC () <UITableViewDelegate, UITableViewDataSource> {
    __strong UIButton *_QRCodeButton;
    __strong UIButton *_searchButton;
    __strong UIButton *_titleButton;
    __strong UIButton *_messageButton;
    UIStatusBarStyle _currentStyle;
}

/** 导航栏前景色 */
@property (strong, nonatomic) UIColor *navBGColor;

/** 顶部轮播 */
@property (weak, nonatomic) SDCycleScrollView *imageRotater;

/** 用户数据 */
@property (strong, nonatomic) ZUserInfo *userInfo;

/** 主界面 */
@property (weak, nonatomic) UITableView *mainView;

/** 界面内容数据源 */
@property (strong, nonatomic) NSArray *dataSource;

@end

@implementation ZHomeVC

#pragma mark - About Navigation

- (void)zConfigNavigation
{
    [super zConfigNavigation];
    _currentStyle = UIStatusBarStyleLightContent;

    _QRCodeButton = [self zButtonWithImage:@"navItem_scan_white" andSelector: @selector(scannerAction)];
    UIBarButtonItem *QRCode = [[UIBarButtonItem alloc] initWithCustomView:_QRCodeButton];
    
    _searchButton = [self zButtonWithImage:@"navItem_search_white" andSelector: @selector(searchAction)];
    UIBarButtonItem *search = [[UIBarButtonItem alloc] initWithCustomView:_searchButton];
    
    _messageButton = [self zButtonWithImage:@"navItem_message_white" andSelector:@selector(collegeAction)];
    UIBarButtonItem *message = [[UIBarButtonItem alloc] initWithCustomView:_messageButton];
    
    _titleButton = [UIButton zButtonWithTitle:@"  华南理工大学广州学院" fontSize:14 textColor:HOME_NAV_FG_COLOR image:[UIImage imageNamed:@"School_Logo"]];
    
    self.navigationItem.leftBarButtonItems = @[[self spacerWithWidth:-10.f], QRCode, search];
    self.navigationItem.titleView = _titleButton;
    self.navigationItem.rightBarButtonItem = message;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return _currentStyle;
}

- (void)scannerAction
{
    // 二维码扫描器
    ZQRCodeScanner *scanner = [[ZQRCodeScanner alloc] init];
    scanner.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:scanner animated:YES];
}

- (void)searchAction
{
    // Todo: 跳转 <首页搜索>
}

- (void)collegeAction
{
    // Todo: 跳转 <学校选择>
}

- (void)messageAction
{
    // Todo: 跳转 <消息中心>
}

#pragma mark - View Life Cycle

- (void)zLoadSubview
{
    [super zLoadSubview];
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // ========== 主界面 ==========
    UITableView *mainView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    mainView.delegate = self;
    mainView.dataSource = self;
    [mainView setBackgroundColor:GENERAL_VIEW_BG_COLOR];
    
    mainView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mainView.showsVerticalScrollIndicator = NO;
    mainView.estimatedRowHeight = 128;
    mainView.rowHeight = UITableViewAutomaticDimension;
    
    [mainView registerNib:[UINib nibWithNibName:@"ZClubCardCell" bundle:nil] forCellReuseIdentifier:ClubCardCellReuseID];
    [mainView registerNib:[UINib nibWithNibName:@"ZActivityCardCell" bundle:nil] forCellReuseIdentifier:ActivityCardCellReuseID];
    [mainView registerNib:[UINib nibWithNibName:@"ZTweetCardCell" bundle:nil] forCellReuseIdentifier:TweetCardCellReuseID];
    [mainView registerClass:[ZCommentHeader class] forHeaderFooterViewReuseIdentifier:HomeHeaderReuseID];
    
    self.mainView = mainView;
    [self.view addSubview:mainView];
    [mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 49, 0));
    }];
    
    // ========== TableHeaderView ==========
    CGFloat RotateHeight = self.view.width / 750.f * 400.f;
    CGFloat stackHeight = 76;
    CGFloat HeadHeight = RotateHeight + stackHeight;
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, HeadHeight)];
    [headerView setBackgroundColor:NAVBAR_BG_COLOR];
    mainView.tableHeaderView = headerView;
    
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(self.view.width, HeadHeight));
    }];
    
    // ========== 广告轮播 ==========
    NSArray *imageNames = @[@"Tools_PlaceHolder", @"Tools_PlaceHolder"];
    
    SDCycleScrollView *imageRotater = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.width, RotateHeight) imageNamesGroup:imageNames];
    [self makeGradientView:imageRotater];
    
    self.imageRotater = imageRotater;
    [headerView addSubview:imageRotater];
    
    // ========== 三大分类入口 ==========
    ZVerticalButton *clubBtn = [ZVerticalButton zVerticalButtonWithTitle:@"学生组织" fontSize:12 color:FONT_MAIN_COLOR image:@"ic_allorganazation"];
    clubBtn.space = 4;
    ZVerticalButton *activityBtn = [ZVerticalButton zVerticalButtonWithTitle:@"校园活动" fontSize:12 color:FONT_MAIN_COLOR image:@"ic_allactivity"];
    activityBtn.space = 4;
    ZVerticalButton *tweetBtn = [ZVerticalButton zVerticalButtonWithTitle:@"组织推文" fontSize:12 color:FONT_MAIN_COLOR image:@"ic_allarticle"];
    tweetBtn.space = 4;
    
    UIStackView *stackView = [[UIStackView alloc] initWithArrangedSubviews:@[clubBtn, activityBtn, tweetBtn]];
    stackView.distribution = UIStackViewDistributionEqualSpacing;
    stackView.alignment = UIStackViewAlignmentCenter;
    
    [headerView addSubview:stackView];
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(imageRotater.mas_bottom);
        make.left.mas_equalTo(headerView).offset(16);
        make.right.mas_equalTo(headerView).offset(-16);
        make.height.mas_equalTo(stackHeight - 4);
    }];
    
    // 弧线效果
    UIImageView *arc = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image_arc"]];
    [headerView addSubview:arc];
    
    [arc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(imageRotater.mas_bottom);
        make.centerX.mas_equalTo(imageRotater);
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self zClearNavBgColorAndSeparator:NO];
    // 设置导航栏为首页样式
    [self zSetNavigationForceColor:HOME_NAV_FG_COLOR];
    
    [self.imageRotater adjustWhenControllerViewWillAppera];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar zReset];
    // 恢复导航栏样式为默认
    [self zSetNavigationForceColor:NAVBAR_FG_COLOR];
}

#pragma mark - Private Method
// 渐变效果
- (void)makeGradientView:(UIView *)view
{
    UIColor *color = [UIColor zColorWithHex:0x333333];
    
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1);
    layer.colors = @[
                     (__bridge id)[color colorWithAlphaComponent:1.0].CGColor,
                     (__bridge id)[color colorWithAlphaComponent:0.5].CGColor,
                     (__bridge id)[color colorWithAlphaComponent:0.0].CGColor,
                     ];
    layer.locations = @[@(0.0), @(0.7f), @(1.0f)];
    
    layer.frame = CGRectMake(0, 0, view.width, 64);
    [view.layer addSublayer:layer];
}

- (UIButton *)zButtonWithImage:(NSString *)imageName andSelector:(SEL)selector
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    UIImage *image = [UIImage imageNamed:imageName];
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

- (UIBarButtonItem *)spacerWithWidth:(CGFloat)width
{
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    space.width = width;
    return space;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // ========== 拖拽时修改导航栏显示效果 ==========
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (offsetY > NAVBAR_CHANGE_START) {
        // 向上拖动, NavigationBar慢慢消失
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_START + NAVBAR_CHANGE_TOTAL - offsetY) / NAVBAR_CHANGE_TOTAL)); // 偏移量越大, 越透明
        [self.navigationController.navigationBar zSetBackgroundColor:[self.navBGColor colorWithAlphaComponent:alpha]];
    }
    else {
        [self.navigationController.navigationBar zSetBackgroundColor:[self.navBGColor colorWithAlphaComponent:0]];
    }
    
    if (offsetY >= NAVBAR_CHANGE_POINT) {
        // 切换蓝色前景状态
        [_QRCodeButton setImage:[UIImage imageNamed:@"navItem_scan_blue"] forState:UIControlStateNormal];
        [_searchButton setImage:[UIImage imageNamed:@"navItem_search_blue"] forState:UIControlStateNormal];
        [_messageButton setImage:[UIImage imageNamed:@"navItem_message_blue"] forState:UIControlStateNormal];
        [_titleButton setTitleColor:NAVBAR_FG_COLOR forState:UIControlStateNormal];
        
        _currentStyle = UIStatusBarStyleDefault;
        [self setNeedsStatusBarAppearanceUpdate];
    } else {
        [_QRCodeButton setImage:[UIImage imageNamed:@"navItem_scan_white"] forState:UIControlStateNormal];
        [_searchButton setImage:[UIImage imageNamed:@"navItem_search_white"] forState:UIControlStateNormal];
        [_messageButton setImage:[UIImage imageNamed:@"navItem_message_white"] forState:UIControlStateNormal];
        [_titleButton setTitleColor:TABBAR_BG_COLOR forState:UIControlStateNormal];
        
        _currentStyle = UIStatusBarStyleLightContent;
        [self setNeedsStatusBarAppearanceUpdate];
    }
    
    // ========== SectionHeader悬停位置修正 ==========
    CGFloat headerHoverY = self.view.width / 750.f * 400.f;
    if (offsetY <= headerHoverY && offsetY >= 0) {
        //拖动距离小于headerHoverY时, 修改偏移值为0
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    } else if(offsetY > headerHoverY) {
        //拖动距离达到headerHoverY时, 修改偏移值为导航高度
        scrollView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = self.dataSource[indexPath.row];
    int value = [dict[@"Type"] intValue];
    
    switch (value) {
        case 0:
        {
            ZClubCardCell *cell = [tableView dequeueReusableCellWithIdentifier:ClubCardCellReuseID];
            return cell;
        }
            break;
        case 1:
        {
            ZActivityCardCell *cell = [tableView dequeueReusableCellWithIdentifier:ActivityCardCellReuseID];
            return cell;
        }
            break;
        case 2:
        {
            ZTweetCardCell *cell = [tableView dequeueReusableCellWithIdentifier:TweetCardCellReuseID];
            return cell;
        }
            break;
        default:
        {
            return nil;
        }
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 36;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ZCommentHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HomeHeaderReuseID];
    header.style = ZTableHeaderStyleDetail;
    header.alignment = ZTableHeaderAlignmentTop;
    [header zSetTitle:@"热门推荐" andImage:@"home_ic_hot"];
    [header zSetBackgroundColor:GENERAL_VIEW_BG_COLOR];
    
    return header;
}


#pragma mark - Getter & Setter

- (UIColor *)navBGColor
{
    if (_navBGColor == nil) {
        _navBGColor = NAVBAR_BG_COLOR;
    }
    return _navBGColor;
}

- (ZUserInfo *)userInfo
{
    // Todo: 获取用户数据, 以下为临时数据
    if (_userInfo == nil) {
        _userInfo = [ZUserInfo sharedInstance];
    }
    return _userInfo;
}

-(NSArray *)dataSource
{
    // ========== Todo: 假数据, 待处理 ==========
    if (_dataSource == nil) {
        _dataSource = @[
                        @{@"Type" : @(0)},
                        @{@"Type" : @(1)},
                        @{@"Type" : @(2)},
                        @{@"Type" : @(0)},
                        @{@"Type" : @(1)},
                        @{@"Type" : @(2)},
                        ];
    }
    return _dataSource;
}

@end
